<?php
namespace app\admin\model;
use think\Db;
use think\Model;
use my\Security;
use app\admin\model\Franchisee as FranchiseeModel;
use think\Cache;

class Member extends Model
{
	 public function __construct()
	{
		parent::__construct();

	}

	//会员列表
    public function memberList($page,$limit,$data,$map=''){
        $map['b.is_del'] = 1;
        $map['a.member_status'] = ['>',0];
        $map['b.false_status'] = 0;
        if (!empty($data['phone'])) {
            $map['b.user_phone'] = ['like',"%".rtrim(Security::encrypt($data['phone']))."%"];
        }
        if(isset($data['member_status']) && $data['member_status'] != ''){
            $map['a.member_status'] = $data['member_status'];
        }
        if (!empty($data['startTime']) && !empty($data['endTime'])) {
            $map['a.start_time'] = ['between',[strtotime($data['startTime']),strtotime($data['endTime'])]];
        }elseif (!empty($data['startTime'])) {
            $map['a.start_time'] = ['>=',strtotime($data['startTime'])];
        }elseif (!empty($data['endTime'])) {
            $map['a.start_time'] = ['<=',strtotime($data['endTime'])];
        }
        //注册省份
        if(isset($data['register_province']) && $data['register_province'] != ''){
            $map['b.register_province'] = $data['register_province'];
        }
        //注册城市
        if(isset($data['register_city']) && $data['register_city'] != ''){
            $map['b.register_city'] = $data['register_city'];
        }
        //分页
        $start = ($page - 1) * $limit;
        $count = Db::name('member')->alias('a')->join('user b','a.uid = b.uid','left')->where($map)->count();
        $field = 'a.*,b.user_phone,a.diamond_number+a.cold_number AS sums';
        $list = Db::name('member')->alias('a')->join('user b','a.uid = b.uid','left')->where($map)->limit($start, $limit)->field($field)->order('sums desc,a.member_status asc,a.member_id desc')->select();
        $memberWalletInfo = $downloadNum = [];
        $uidStr = '';
        foreach($list as $key=>$value){
            $list[$key]['user_phone']   = Security::decrypt($value['user_phone']);
            //获取第一推荐人/上上级推挤人手机号
            $phoneOne          = Cache::get($value['directly']);
            if(!empty($value['directly']) && empty($phoneOne)){
                $phoneOne = Db::name('user')->where(['uid'=>$value['directly'],'is_del'=>1,'false_status'=>0])->value('user_phone as phoneOne');
                Cache::set($value['directly'],$phoneOne);
            }
            $phoneTwo          = Cache::get($value['superior']);
            if(!empty($value['superior']) && empty($phoneTwo)){
                $phoneTwo = Db::name('user')->where(['uid'=>$value['superior'],'is_del'=>1,'false_status'=>0])->value('user_phone as phoneTwo');
                Cache::set($value['superior'],$phoneTwo);
            }
            $list[$key]['phone']        = Security::decrypt($phoneOne).' / '.Security::decrypt($phoneTwo);
            $start_time = $end_time = '';
            if(!empty($value['start_time'])){
                $start_time = date("Y-m-d",$value['start_time']);
            }
            if(!empty($value['end_time'])){
                $end_time = date("Y-m-d",$value['end_time']);
            }
            $list[$key]['time'] = $start_time.' / '.$end_time;
            if($value['member_status'] == 1){
                $list[$key]['statuName'] = '已开启';
            }elseif($value['member_status'] == 2){
                $list[$key]['statuName'] = '<span style="color: red">已过期</span>';
            }else{
                $list[$key]['statuName'] = '<span style="color:#b2b2b2">未开启</span>';
            }
            $list[$key]['peronNum'] = $value['diamond_number'].'/'.$value['cold_number'];
            $list[$key]['orderNum'] = $value['diamond_order_count'].'/'.$value['cold_order_count'];
            $list[$key]['levelName']= "V".$value['level'];
            $uidStr .= $value['uid'].',';
        }
        //查询佣金金额
        $memberWalletInfo = Db::name('member_wallet')->where(['uid'=>['in',rtrim($uidStr,',')]])->field('uid,sum_money,wallet_money')->select();
        $memberWalletReult = [];
        foreach ($memberWalletInfo as $key=>$value){
            $memberWalletReult[$value['uid']]['sum_money']      = $value['sum_money'];
            $memberWalletReult[$value['uid']]['wallet_money']   = $value['wallet_money'];
        }
        //查询统计下载APP数量
        $downloadNum    = self::downloadAppNum($uidStr);
        //查询顺风车车主人数
        $userArrList    = Db::name('user')->where(['is_fr'=>1,'is_del'=>1,'false_status'=>0,'referee_id'=>['in',rtrim($uidStr,',')]])->field('uid,referee_id')->select();
        $userArrResult  = [];
        foreach ($userArrList as $key=>$value){
            $userArrResult[$value['referee_id']][] = $value['uid'];
        }
        $userArrTwoRes = [];
        foreach (explode(',',$uidStr) as $value){
            $two_fr_num  = count($userArrResult[$value]);
            if(!empty($two_fr_num)){
                $userArrTwoRes[$value] = Db::name('user')->where(['referee_id'=>['in',implode(',',$userArrResult[$value])],'is_del'=>1,'false_status'=>0,'is_fr'=>1])->field('uid')->count();
            }else{
                $userArrTwoRes[$value] = 0;
            }
        }
        foreach($list as $key=>$value){
            $list[$key]['sum_money']    = $memberWalletReult[$value['uid']]['sum_money']/100;
            $list[$key]['wallet_money'] = $memberWalletReult[$value['uid']]['wallet_money']/100;
            $list[$key]['one_fr_num']   = count($userArrResult[$value['uid']]);
            $list[$key]['two_fr_num']   = $userArrTwoRes[$value['uid']];
            $list[$key]['downloadAppNum'] = $downloadNum[$value['uid']]['oneMmberNumber'].'/'.$downloadNum[$value['uid']]['twoMemberNumber'];
        }
        return array(
            'code'  => 0,
            'msg'   => '',
            'count' => $count,
            'data'  => $list
        );
    }

    //查询APP下载量 根据登录时间断定
    public function downloadAppNum($uidStr=''){
        $uidStr = rtrim($uidStr,',');
        $list = Db::name('user')->where(['referee_id'=>['in',$uidStr],'is_del'=>1,'false_status'=>0,'last_login_time'=>['>','0']])->field('uid,referee_id')->select();
        $result = [];
        foreach ($list as $key=>$value){
            $result[$value['referee_id']][] = $value['uid'];
        }
        $data = [];
        foreach (explode(',',$uidStr) as $value){
            $data[$value]['oneMmberNumber']  = count($result[$value]);
            if(!empty($data[$value]['oneMmberNumber'])){
                $data[$value]['twoMemberNumber'] = Db::name('user')->where(['referee_id'=>['in',implode(',',$result[$value])],'is_del'=>1,'false_status'=>0,'last_login_time'=>['>','0']])->field('uid')->count();
            }else{
                $data[$value]['twoMemberNumber'] = 0;
            }
        }
        return $data;
    }


    //会员流水记录
    public function memberRechargeList($page,$limit,$data,$map=[]){
        $map['b.is_del'] = 1;
        if (!empty($data['phone'])) {
            $map['b.user_phone'] = ['like',"%".rtrim(Security::encrypt($data['phone']))."%"];
        }
        if (!empty($data['startTime']) && !empty($data['endTime'])) {
            $map['a.add_time'] = ['between',[strtotime($data['startTime']),strtotime($data['endTime'])]];
        }elseif (!empty($data['startTime'])) {
            $map['a.add_time'] = ['>=',strtotime($data['startTime'])];
        }elseif (!empty($data['endTime'])) {
            $map['a.add_time'] = ['<=',strtotime($data['endTime'])];
        }
        //分页
        $start = ($page - 1) * $limit;
        $count = Db::name('member_recharge')->alias('a')->join('user b','a.uid = b.uid','left')->where($map)->count();
        $field = 'a.*,b.user_phone';
        $list = Db::name('member_recharge')->alias('a')->join('user b','a.uid = b.uid','left')
            ->where($map)->limit($start, $limit)->field($field)
            ->order('a.id desc')->select();
        foreach($list as $key=>$value){
            $list[$key]['user_phone']   = Security::decrypt($value['user_phone']);
            $list[$key]['money']        = $value['money']/100;
            $list[$key]['order_money']  = $value['order_money']/100;
            $list[$key]['add_time']     = date("Y-m-d H:i:s",$value['add_time']);
            $list[$key]['typeName']     = typeName($value['type']);
            $list[$key]['orderTypeName']= orderTypeName($value['order_type']);
            $list[$key]['ratio']        = !empty($value['ratio'])?$value['ratio']." %":"";
        }
        return array(
            'code'  => 0,
            'msg'   => '',
            'count' => $count,
            'data'  => $list
        );
    }

    //获取会员信息
    public function memberInfoDetail($uid=''){
        $memberInfo = Db::name('member')->alias('a')->join('member_wallet b','a.uid = b.uid','left')->field("a.*,b.sum_money,b.wallet_money")->where(['a.uid'=>$uid])->find();
        return $memberInfo;
    }
    //推广记录
    public function memberExtestionList($page,$limit,$uid,$data){
        $map['a.referee_id'] = $uid;
        if (!empty($data['phone'])) {
            $map['a.user_phone'] = ['like',"%".rtrim(Security::encrypt($data['phone']))."%"];
        }
        if (!empty($data['startTime']) && !empty($data['endTime'])) {
            $map['a.register_time'] = ['between',[strtotime($data['startTime']),strtotime($data['endTime'])]];
        }elseif (!empty($data['startTime'])) {
            $map['a.register_time'] = ['>=',strtotime($data['startTime'])];
        }elseif (!empty($data['endTime'])) {
            $map['a.register_time'] = ['<=',strtotime($data['endTime'])];
        }
        //注册省份
        if(isset($data['province_id']) && $data['province_id'] != ''){
            $map['a.register_province'] = $data['province_id'];
        }
        //注册城市
        if(isset($data['city_id']) && $data['city_id'] != ''){
            $map['a.register_city'] = $data['city_id'];
        }
        //分页
        $start = ($page - 1) * $limit;
        if($data['user_status'] == 2){
            $oneList = Db::name('user')->alias('a')->join('member b','a.uid = b.uid','left')->field("a.uid,b.level,a.user_phone,a.register_time")->where(['a.referee_id'=>$uid])->order('a.uid desc')->select();
            $uidStr = '';
            if(!empty($oneList)){
                foreach ($oneList as $key=>$value){
                    $uidStr .= $value['uid'].',';
                }
            }
            $uidStr = rtrim($uidStr,',');
            $map['a.referee_id'] = ['in',rtrim($uidStr,',')];
            if(empty($uidStr)){
                return array('code'  => 0,'msg'   => '','count' => '0','data'  => []);
            }
        }
        $list  = Db::name('user')->alias('a')->join('member b','a.uid = b.uid','left')->field("a.uid,a.is_fr,b.level,a.user_phone,a.register_time,a.register_province,a.register_city")->where($map)->limit($start, $limit)->order('a.uid desc')->select();
        $count = Db::name('user')->alias('a')->join('member b','a.uid = b.uid','left')->where($map)->limit($start, $limit)->order('a.uid desc')->count();
        $result = [];
        foreach ($list as $key=>$value){
            //查询省份
            $list[$key]['province_name']    = Db::name('region')->where(['region_id'=>$value['register_province']])->value('region_name');
            //查询城市
            $list[$key]['city_name']        = Db::name('region')->where(['region_id'=>$value['register_city']])->value('region_name');
            $list[$key]['user_phone']       = Security::decrypt($value['user_phone']);
            $list[$key]['register_time']    = date("Y-m-d H:i:s",$value['register_time']);
            $result                         = FranchiseeModel::orderSumInfo($value['uid']);
            $list[$key]['ordersnNum']       = $result['ordersnNum'];
            $list[$key]['orderMoney']       = $result['orderMoney'];
            if(!empty($value['level'])){
                $list[$key]['levelName']    = "V".$value['level'];
            }else{
                $list[$key]['levelName']    = '暂未开通会员';
            }
            if(!empty($value['is_fr'])){
                $list[$key]['is_fr_name']   = "是";
            }else{
                $list[$key]['is_fr_name']   = "否";
            }
        }
        return array(
            'code'  => 0,
            'msg'   => '',
            'count' => $count,
            'data'  => $list
        );
    }

    //查询佣金记录
    public function memberCommissionList($page,$limit,$uid=''){
        $start = ($page - 1) * $limit;
        $list = Db::name('member_recharge')->where(['uid'=>$uid])->limit($start, $limit)->select();
        $count = Db::name('member_recharge')->where(['uid'=>$uid])->limit($start, $limit)->count();
        $i = 1;
        foreach ($list as $key=>$value){
            $list[$key]['money']        = $value['money']/100;
            $list[$key]['order_money']  = $value['order_money']/100;
            $list[$key]['add_time']     = date("Y-m-d H:i:s",$value['add_time']);
            $list[$key]['typeName']     = typeName($value['type']);
            $list[$key]['orderTypeName']= orderTypeName($value['order_type']);
            $list[$key]['ratio']        = !empty($value['ratio'])?$value['ratio']." %":"";
            $list[$key]['number'] = $i;
            $i++;
        }
        return array(
            'code'  => 0,
            'msg'   => '',
            'count' => $count,
            'data'  => $list
        );
    }
}
